// utils/exportExcelWithImage.js
// import ExcelJS from 'exceljs';
// import { saveAs } from 'file-saver';

import XLSX from 'xlsx'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver';

export async function exportProductionOrder(data, fileName = '生产订单.xlsx') {
  // 创建工作簿
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('生产订单');

  // ============= 设置表格样式 =============
  // 标题样式
  const titleStyle = {
    font: { bold: true, size: 16, color: { argb: 'FF000000' } },
    alignment: { horizontal: 'left' }
  };

  // 表头样式
  const headerStyle = {
    font: { bold: true, color: { argb: 'FFFFFFFF' } },
    fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF4472C4' } },
    border: {
      top: { style: 'thin', color: { argb: 'FF000000' } },
      left: { style: 'thin', color: { argb: 'FF000000' } },
      bottom: { style: 'thin', color: { argb: 'FF000000' } },
      right: { style: 'thin', color: { argb: 'FF000000' } }
    }
  };

  // 数据单元格样式
  const cellStyle = {
    border: {
      top: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      left: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      bottom: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      right: { style: 'thin', color: { argb: 'FFD9D9D9' } }
    }
  };

  // ============= 添加主表数据 =============
  // 添加标题
  worksheet.mergeCells('A1:H1');
  const titleCell = worksheet.getCell('A1');
  titleCell.value = '普通股票, 翻单生产单';
  titleCell.style = titleStyle;

  // 添加主表数据行
  const mainDataRows = [
    ['生产单号', data.productionNo, '客人下单日期', data.orderDate, '尺码', data.size, '生产线', data.productionLine],
    ['客人订单号', data.customerOrderNo, '出货要求交期', data.deliveryDate, '低角', data.lowAngle, '客户代码', data.customerCode],
    ['PLU号', data.pluNo, '订单数', data.orderQuantity, '量守', data.measure, '冲模编号', data.moldNo],
    ['客称号', data.customerTitle, '生产数', data.productionQuantity, '开放位', data.openPosition, '', ''],
    ['TS完成日期', data.tsCompletionDate, 'TCS完成日期', data.tcsCompletionDate, '订单类别', data.orderType, '', '']
  ];

  // 添加主表数据
  mainDataRows.forEach((row, rowIndex) => {
    const worksheetRow = worksheet.addRow(row);
    worksheetRow.eachCell((cell, colNumber) => {
      // 设置表头单元格样式
      if (colNumber % 2 === 1) { // 奇数列为标题列
        cell.style = { ...headerStyle, ...cellStyle };
      } else {
        cell.style = cellStyle;
      }
    });
  });

  // ============= 添加图例 =============
  // 添加空行
  worksheet.addRow([]);
  
  // 添加图例标题
//   const exampleTitleRow = worksheet.addRow(['图例:']);
//   exampleTitleRow.getCell(1).style = { font: { bold: true } };
//   worksheet.mergeCells(`A${exampleTitleRow.number}:H${exampleTitleRow.number}`);
  
  // 添加图例内容
//   const exampleContentRow1 = worksheet.addRow(['数据来源:']);
//   exampleContentRow1.getCell(1).style = { indent: 1 };
//   worksheet.mergeCells(`A${exampleContentRow1.number}:H${exampleContentRow1.number}`);
  
//   const exampleContentRow2 = worksheet.addRow(['横坐标:', data.exampleHorizontal]);
//   exampleContentRow2.getCell(1).style = { indent: 2 };
//   worksheet.mergeCells(`A${exampleContentRow2.number}:H${exampleContentRow2.number}`);
  
//   const exampleContentRow3 = worksheet.addRow(['纵坐标:', data.exampleVertical]);
//   exampleContentRow3.getCell(1).style = { indent: 2 };
//   worksheet.mergeCells(`A${exampleContentRow3.number}:H${exampleContentRow3.number}`);

  // 添加分隔线
//   worksheet.addRow(['---']);
//   worksheet.mergeCells(`A${worksheet.rowCount}:H${worksheet.rowCount}`);

  // 3. 添加6-10行空数据
  for (let i = 6; i <= 10; i++) {
    worksheet.addRow(new Array(8).fill(''));
  }

  // 4. 设置行高
  for (let i = 6; i <= 10; i++) {
    worksheet.getRow(i).height = 20;
  }

  // ========== 第一段：合并第1列(A列) ==========
  worksheet.mergeCells('A6:A10');
  const firstSegment = worksheet.getCell('A6');
  firstSegment.value = "第一段内容";
  firstSegment.style = {
    alignment: { vertical: 'middle', horizontal: 'center' },
    font: { bold: true, size: 12 },
    border: {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' }
    }
  };

  // ========== 第二段：合并第2-6列(B-F列)并添加图片 ==========
  worksheet.mergeCells('B6:F10');
  const secondSegment = worksheet.getCell('B6');
  secondSegment.value = ""; // 清空内容以便显示图片
  
  // 添加图片 (需要先转换为base64)
  //const imageBase64 = await getDemoImageBase64(); // 获取示例图片
  if (data.imageBase64) {
    const imageId = workbook.addImage({
      base64: data.imageBase64,
      extension: 'png'
    });
    
    // 图片定位在合并的单元格内
    worksheet.addImage(imageId, {
      tl: { col: 2, row: 5 },  // B6 (注意: row索引从0开始)
      br: { col: 6, row: 10 }, // F10
      ext: { width: 400, height: 100 }
    //   editAs: 'oneCell' // 图片随单元格移动和调整大小
    });
  }

  // ========== 第三段：合并第7-8列(G-H列) ==========
  worksheet.mergeCells('G6:H10');
  const thirdSegment = worksheet.getCell('G6');
  thirdSegment.value = "第三段内容";
  thirdSegment.style = {
    alignment: { vertical: 'middle', horizontal: 'center' },
    font: { italic: true },
    fill: {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF2F2F2' }
    }
  };

  // ============= 添加物料清单 =============
  // 添加物料清单标题
  const materialTitleRow = worksheet.addRow(['外购物料清单']);
  materialTitleRow.getCell(1).style = titleStyle;
  worksheet.mergeCells(`A${materialTitleRow.number}:F${materialTitleRow.number}`);

  // 添加物料清单表头
  const materialHeader = worksheet.addRow(['类别', '物料编码', '物料描述', '数量', '单位', '备注']);
  materialHeader.eachCell(cell => {
    cell.style = headerStyle;
  });

  // 添加物料数据
  data.materialList.forEach(item => {
    const row = worksheet.addRow([
      item.category,
      item.materialCode,
      item.materialDescription,
      item.quantity,
      item.unit,
      item.remark
    ]);
    
    // 设置物料描述列自动换行
    const descCell = row.getCell(3);
    descCell.style = { 
      ...cellStyle,
      alignment: { wrapText: true }
    };
  });

  // ============= 设置列宽 =============
  worksheet.columns = [
    { width: 15 }, // 类别
    { width: 20 }, // 物料编码
    { width: 60 }, // 物料描述
    { width: 12 },  // 数量
    { width: 12 },  // 单位
    { width: 20 }  // 备注
  ];

  // ============= 添加图片 =============
  // 注意：ExcelJS 在前端无法直接添加本地图片，需要先将图片转换为Base64
//   if (data.imageBase64) {
//     const imageId = workbook.addImage({
//       base64: data.imageBase64,
//       extension: 'png'
//     });
    
//     worksheet.addImage(imageId, {
//       tl: { col: 2, row: 7 },
//       ext: { width: 400, height: 100 }
//     });

  
//   }

  // ============= 导出文件 =============
  const buffer = await workbook.xlsx.writeBuffer();
  saveAs(new Blob([buffer]), fileName);
}